﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace COFE.Web
{
    public interface ISupportLinkTemplates : ILinkContainer
    {
        /// <summary>
        /// Get a list of Link templates
        /// </summary>
        /// <returns></returns>
        IEnumerable<LinkTemplate> GetLinkTemplates();

        /// <summary>
        /// Get dictionary of parameters for link templates, e.g. Entry's #id#
        /// </summary>
        /// <returns></returns>
        Dictionary<string, string> GetLinkParameterDic();
    }

    public static class ISupportLinkTemplatesExtension
    {
        public static Link CreateLink(this LinkTemplate template,
           Dictionary<string, string> localLookupDictionary = null)
        {
            if (localLookupDictionary == null)
                throw new Exception();

            string uri = template.UriTemplate
                   .Replace(ServiceConstants.Templates
                   .GlobalLookupDictionary["#host#"], ServiceConstants.Host);
            foreach (var keyValue in localLookupDictionary)
                uri = uri.Replace(keyValue.Key, keyValue.Value);
            foreach (var keyValue in ServiceConstants.Templates.GlobalLookupDictionary)
                uri = uri.Replace(keyValue.Key, keyValue.Value);

            if (template.RelationType == RelationType.Property)
                return new Link(template.MediaType, template.RelationString, uri);

            return new Link(template.MediaType, template.RelationType, uri);
        }

        public static Link CreateLink(this ISupportLinkTemplates slt, LinkTemplate template, 
            Dictionary<string, string> localLookupDictionary = null)
        {
            if (localLookupDictionary == null)
                localLookupDictionary = slt.GetLinkParameterDic();
            if (localLookupDictionary == null)
                throw new Exception();

            return template.CreateLink(localLookupDictionary);
        }

        public static IEnumerable<Link> CreateLinks(this ISupportLinkTemplates slt)
        {
            var localLookupDictionary = slt.GetLinkParameterDic();
            foreach (var template in slt.GetLinkTemplates())
            {
                yield return CreateLink(slt, template, localLookupDictionary);                
            }
        }

        public static Link FindLink(this ISupportLinkTemplates slt, string rel)
        {
            if (rel.Equals("default", StringComparison.InvariantCultureIgnoreCase))
                return slt.CreateLinks().First();

            var foundLink = (slt.CreateLinks().FirstOrDefault((link) =>
                        { return link.RelationString.Equals(rel, StringComparison.InvariantCultureIgnoreCase); }));
            if (foundLink == null)
                throw new KeyNotFoundException(rel);
            return foundLink;
        }
    }
}
